<template>
  <div>
    <!-- 头部面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        show-icon
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="setrow">
        <span>选择商品分类：</span>
        <!-- 级联选择框 -->
        <el-cascader
          v-model="seletekeys"
          :options="catelist"
          :props="cateprops"
          @change="seletekyes"
        ></el-cascader>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="tabsclick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isdissble"
            @click="adddialblock"
          >
            添加参数</el-button
          >
          <!-- 动态参数的表格 -->
          <el-table :data="manydata" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closetag(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="##"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="updatapas(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  @click="delmanydata(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isdissble"
            @click="adddialblock"
          >
            添加属性</el-button
          >
          <!-- 静态参数表 -->
          <el-table :data="onlydata" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closetag(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="##"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="updataonly(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  @click="delonlydata(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titiletext"
      :visible.sync="adddialong"
      width="50%"
      @close="closedial"
    >
      <el-form
        :model="addinfo"
        :rules="addinforules"
        ref="addinfo"
        label-width="100px"
      >
        <el-form-item :label="titiletext" prop="attr_name">
          <el-input v-model="addinfo.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialong = false">取 消</el-button>
        <el-button type="primary" @click="queraddinfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑动态参数对话框 -->
    <el-dialog title="编辑动态属性" :visible.sync="updatadialog" width="50%">
      <el-form
        :model="updatapasinfo"
        :rules="updatapasinforules"
        ref="updatapas"
        label-width="100px"
      >
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="updatapasinfo.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updatadialog = false">取 消</el-button>
        <el-button type="primary" @click="querupdatapas">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑静态属性对话框 -->
    <el-dialog title="编辑静态参数" :visible.sync="uponlydialog" width="50%">
      <el-form
        :model="uponlyinfo"
        :rules="uponlyinforules"
        ref="uponlypas"
        label-width="100px"
      >
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="uponlyinfo.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uponlydialog = false">取 消</el-button>
        <el-button type="primary" @click="queruponly">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品分类列表
      catelist: [],
      //级联选择框的选择的数据
      seletekeys: [],
      //级联选择器的配置对象
      cateprops: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      //tab页签的选择
      activeName: "many",
      //many动态参数的数据
      manydata: [],
      //only静态属性的数据
      onlydata: [],
      //添加属性对话框的显示隐藏
      adddialong: false,
      //添加属性的表单数据
      addinfo: {
        attr_name: "",
      },
      //添加属性的表单验证规则
      addinforules: {
        attr_name: [{ required: true, message: "填写名称", trigger: "blur" }],
      },
      //编辑动态参数对话框的显示与隐藏
      updatadialog: false,
      //编辑对话框的数据信息
      updatapasinfo: {},
      //编辑动态参数对话框的验证规则
      updatapasinforules: {
        attr_name: [{ required: true, message: "填写名称", trigger: "blur" }],
      },
      // 静态属性对话框的显示与隐藏
      uponlydialog: false,
      //编辑静态属性对话框的数据信息
      uponlyinfo: {},
      //编辑静态属性对话框的验证规则
      uponlyinforules: {
        attr_name: [{ required: true, message: "填写名称", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getcatelist();
  },
  methods: {
    //获取商品列表
    async getcatelist() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error("获取列表失败");
      this.catelist = res.data;
      this.$message.success("获取列表成功");
    },
    //获取动态参数和静态属性的列表
    async gettablist() {
      const { data: res } = await this.$http.get(
        `categories/${this.keysid}/attributes`,
        { params: { sel: this.activeName } }
      );
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        //给每一行表格中的tag标签都添加单独的属性
        //要用this.$set给添加的属性有响应式
        //tag标签中添加tag标签的input
        this.$set(item, "inputVisible", false);
        //input输入的内容
        this.$set(item, "inputValue", "");
      });
      console.log(this.arrdata);

      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.$message.success("获取数据");
      if (this.activeName === "many") this.manydata = res.data;
      this.onlydata = res.data;
    },
    //级联选择框获取选择的数据
    async seletekyes(keys) {
      if (keys.length < 3) {
        this.seletekeys = [];
        this.manydata=[]
        this.onlydata=[]
        return this.$message.error("亲选择三级分类");
      }
      this.seletekeys = keys;
      //当级联选择框那个里面的数据发生改变时发送请求
      this.gettablist();
    },
    //tab的点击事件
    tabsclick() {
      //切换tab页签时也发送数据请求
      if (this.keysid) this.gettablist();
      console.log(this.onlydata);
      console.log(this.manydata);

      console.log(this.activeName);
    },
    //添加属性按钮的事件
    adddialblock() {
      this.adddialong = true;
    },
    //添加属性对话框关闭事件
    closedial() {
      this.$refs.addinfo.resetFields();
    },
    //dail对话框确定按钮
    async queraddinfo() {
      this.$refs.addinfo.validate((valid) => {
        if (!valid) return;
      });
      const { data: res } = await this.$http.post(
        `categories/${this.keysid}/attributes`,
        {
          attr_name: this.addinfo.attr_name,
          attr_sel: this.activeName,
        }
      );
      if (res.meta.status !== 201) return this.$message.error("添加属性失败");
      this.gettablist();
      this.$message.success("添加数据成功");
      this.adddialong = false;
    },
    //修改动态参数
    async updatapas(row) {
      const { data: res } = await this.$http.get(
        `categories/${this.seletekeys[2]}/attributes/${row.attr_id}`,
        {
          params: {
            arrt_sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.$message.success("获取数据");
      console.log(res);

      this.updatapasinfo = res.data;
      this.updatadialog = true;
    },
    //修改动态参数对话框的确认事件
    async querupdatapas() {
      const { data: res } = await this.$http.put(
        `categories/${this.seletekeys[2]}/attributes/${this.updatapasinfo.attr_id}`,
        {
          attr_name: this.updatapasinfo.attr_name,
          attr_sel: this.activeName,
        }
      );
      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.$message.success("获取数据");
      this.updatadialog = false;
      this.gettablist();
    },
    //删除动态属性
    async delmanydata(row) {
      const msg = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (msg !== "confirm") return this.$message.error("取消删除成功");
      const { data: res } = await this.$http.delete(
        `categories/${this.keysid}/attributes/${row.attr_id}`
      );
      console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("动态参数删除失败");
      this.$message.success("动态参数删除成功");
      this.gettablist();
    },
    //编辑静态参数按钮
    async updataonly(row) {
      const { data: res } = await this.$http.get(
        `categories/${this.seletekeys[2]}/attributes/${row.attr_id}`,
        {
          params: {
            arrt_sel: this.activeName,
          },
        }
      );
      console.log(res);

      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.$message.success("获取数据");
      this.uponlyinfo = res.data;
      this.uponlydialog = true;
    },
    //编辑静态参数对话框的确认事件
    async queruponly() {
      const { data: res } = await this.$http.put(
        `categories/${this.seletekeys[2]}/attributes/${this.uponlyinfo.attr_id}`,
        {
          attr_name: this.uponlyinfo.attr_name,
          attr_sel: this.activeName,
        }
      );
      console.log(res);

      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.$message.success("获取数据");
      this.uponlydialog = false;
      this.gettablist();
    },
    //删除静态参数
    async delonlydata(row) {
      const msg = await this.$confirm(
        "此操作将永久删除静态参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (msg !== "confirm") return this.$message.error("取消删除成功");
      const { data: res } = await this.$http.delete(
        `categories/${this.keysid}/attributes/${row.attr_id}`
      );
      console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("静态参数删除失败");
      this.$message.success("静态参数删除成功");
      this.gettablist();
    },
    async sendsave(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.keysid}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(","),
        }
      );
      if (res.meta.status !== 200) return this.$message.error("添加失败");
      this.$message.success("添加成功");
    },
    //tag标签中文本框事件
    handleInputConfirm(row) {
      console.log("ok");
      //判断input里面的值是否合法
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      //将合法的值添加到row.attr_vals数组当中
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.sendsave(row)
    },
    // 显示文本框
    showInput(row) {
      row.inputVisible = true;
      //自动获得焦点
      this.$nextTick((_) => {
        //第一个refs是获得el-input组件的实例对象
        //第二个refs是获得el-input组件中原生dom元素input
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //删除tag标签
    closetag(i, row) {
      row.attr_vals.splice(i, 1);
      this.sendsave(row)
    },
  },
  computed: {
    //添加按钮是否禁用
    isdissble() {
      if (this.seletekeys.length === 3) return false;
      return true;
    },
    //分类id
    keysid() {
      console.log(this.seletekeys);
      if (this.seletekeys.length === 3) return this.seletekeys[2];
      return null;
    },
    //添加属性对话框的标题
    titiletext() {
      if (this.activeName === "many") return "动态参数";
      return "静态属性";
    },
  },
};
</script>

<style scoped>
.el-card {
  margin-top: 20px;
}
.setrow {
  margin: 10px 10px;
}
.input-new-tag {
  width: 80px;
}
.el-tag {
  margin: 0 5px;
}
</style>